<template>
	<view class="container">
		<!-- 可滚动内容 -->
		<scroll-view class="scroll-view" scroll-y @scroll="handleScroll" :scroll-top="scrollTop">
			<!-- 用户信息 -->
			<AuthorHeader :user-info="userInfo" :useradditionalinfo="useradditionalinfo" :panel-data="panelData"
				:is-followed="isFollowed" :follow-id="followId" @follow-change="handleFollowChange"
				@image-error="handleImageError" />

			<!-- 内容区域 -->
			<AuthorContentSection :tabs="tabs" :active-tab="activeTab" :posts="posts" :item-width="itemWidth"
				@tab-change="switchTab" @post-click="handlePostClick" />
		</scroll-view>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted } from 'vue'
	import AuthorHeader from './components/AuthorHeader.vue'
	import AuthorContentSection from './components/AuthorContentSection.vue'
	import { getPostForUser } from '@/api/post/post'
	import type { PostBasicInfo } from '@/api/post/post'
	import { onLoad } from '@dcloudio/uni-app'
	import { getUserInfoByUserId } from '@/api/user/user'
	import { getInfoByUserId } from '@/api/useradditionalinfo/info'
	import { getFollowedByFansId, getPanelDataForUser, type UserFollowVO, type PanelData } from '@/api/follow/follow'
	import useUserStore from '@/store/modules/user'

	const userStore = useUserStore()

	interface PanelDataItem {
		value : number | string
		label : string
	}

	interface ScrollEvent {
		detail : {
			scrollTop : number
		}
	}

	// 用户信息数据
	const userInfo = ref()
	const useradditionalinfo = ref()
	const isFollowed = ref(false)
	const followId = ref<number | undefined>()

	// 响应式数据 - 初始化为空数组，将通过API获取
	const panelData = ref<PanelDataItem[]>([])



	const navBarBackground = ref<string>('red')
	const titleOpacity = ref<number>(0)
	const scrollTop = ref<number>(0)
	const activeTab = ref<number>(0)
	const tabs = ref<string[]>(['笔记', '收藏', '赞过'])
	const posts = ref<PostBasicInfo[]>()
	const itemWidth = ref<number>(0)

	const authorUserId = ref()

	// 检查关注状态
	const checkFollowStatus = async () => {
		try {
			// 如果用户未登录或者是作者本人，不需要检查关注状态
			if (!userStore.user || !userStore.user.userId || authorUserId.value === userStore.user.userId) {
				isFollowed.value = false
				return
			}

			// 获取当前用户的关注列表
			const res = await getFollowedByFansId(userStore.user.userId)
			if (res.code === 200 && res.data) {
				const followList : UserFollowVO[] = res.data
				// 检查是否已关注当前用户
				const followItem = followList.find(follow => follow.followedUserId === authorUserId.value)
				isFollowed.value = !!followItem
				followId.value = followItem?.id
			}
		} catch (error) {
			console.error('获取关注状态失败:', error)
		}
	}

	// 处理关注状态变化
	const handleFollowChange = (newFollowState : boolean) => {
		isFollowed.value = newFollowState
		// 如果需要，可以重新获取关注状态以更新followId
		if (newFollowState) {
			checkFollowStatus()
		} else {
			followId.value = undefined
		}
	}

	// 移除原来的handleFollow方法，因为现在由AuthorHeader组件处理

	const calculateLayout = () : void => {
		const { windowWidth } = uni.getWindowInfo()
		itemWidth.value = (windowWidth - 32) / 2
	}

	const handleScroll = (e : ScrollEvent) : void => {
		const scrollTopValue = e.detail.scrollTop
		titleOpacity.value = Math.min(scrollTopValue / 100, 1)
		navBarBackground.value = `rgba(255,255,255,${Math.min(scrollTopValue / 80, 0.98)})`
	}

	const getAuthorInfo = async () => {
		const res = await getUserInfoByUserId(authorUserId.value)
		userInfo.value = res.data
	}

	const getAuthorAdditionalInfo = async () => {
		const res = await getInfoByUserId(authorUserId.value)
		useradditionalinfo.value = res.data
	}

	const switchTab = (index : number) : void => {
		activeTab.value = index
		// 这里可以根据不同的tab加载不同的数据
		loadPostsByTab(index)
	}

	const loading = ref<boolean>(false);

	// 加载tab数据
	const loadPostsByTab = async (tabIndex : number) : Promise<void> => {
		loading.value = true;
		try {
			const type = tabIndex + 1; // 0->1, 1->2, 2->3
			const query = {
				pageNum: 1,
				pageSize: 20
			};

			const result = await getPostForUser(type, authorUserId.value, query);

			if (result.code === 200) {
				posts.value = result.rows || [];
			} else {
				uni.showToast({
					title: result.msg || '加载失败',
					icon: 'none'
				});
			}
		} catch (error) {
			uni.showToast({
				title: '网络错误',
				icon: 'none'
			});
		} finally {
			loading.value = false;
		}
	}

	const handlePostClick = (post : PostBasicInfo) : void => {
		console.log('点击帖子:', post)
		// 跳转到帖子详情页
		uni.navigateTo({
			url: `/pages/post/postDetail?id=${post.id}`
		})
	}

	const handleImageError = () : void => {
		console.log('图片加载失败')
		userInfo.value.avatar = '/static/images/default-avatar.png'
	}

	// 页面加载时获取参数
	onLoad((options) => {
		if (options?.id) {
			authorUserId.value = Number(options.id)
		}
	})

	// 获取面板数据
	const getPanelData = async () => {
		try {
			const res = await getPanelDataForUser(authorUserId.value)
			if (res.code === 200 && res.data && res.data.length > 0) {
				// 后端返回的是数组格式，取第一个元素
				const data: PanelData = res.data[0]
				// 转换数据格式
				panelData.value = [
					{
						value: data.followCount || 0,
						label: '关注'
					},
					{
						value: formatCount(data.fansCount || 0),
						label: '粉丝'
					},
					{
						value: formatCount(data.postLikeCount || 0),
						label: '获赞'
					}
				]
			}
		} catch (error) {
			console.error('获取面板数据失败:', error)
			// 设置默认值
			panelData.value = [
				{ value: 0, label: '关注' },
				{ value: 0, label: '粉丝' },
				{ value: 0, label: '获赞' }
			]
		}
	}

	// 格式化数字显示（如：12800 -> 12.8万）
	const formatCount = (count: number): string => {
		if (count >= 10000) {
			return (count / 10000).toFixed(1) + '万'
		}
		return count.toString()
	}

	// 生命周期
	onMounted(() => {
		calculateLayout()
		loadPostsByTab(0) // 初始加载第一个tab的数据
		getAuthorInfo()
		getAuthorAdditionalInfo()
		getPanelData() // 获取面板数据
		checkFollowStatus() // 检查关注状态
	})
</script>

<style lang="scss" scoped>
	// 只保留容器相关的样式
	.container {
		height: 100vh;
	}

	.scroll-view {
		height: 100%;
	}
</style>